package cn.yanhu.kuwanapp.wxapi

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.TypedArray
import android.os.Build
import android.os.Bundle
import cn.yanhu.kuwanapp.event.AccountAuthEvent
import cn.yanhu.kuwanapp.event.AccountLoginEvent
import cn.yanhu.kuwanapp.utils.ext.logprocess
import cn.yanhu.kuwanapp.utils.third.AccountReqType
import cn.yanhu.kuwanapp.utils.third.ThirdAccountHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.core.LiveEvent
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler

/**
 *微信回到界面
 *@author woochen
 *@time 2019/11/29 9:43
 */
class WXEntryActivity : Activity(), IWXAPIEventHandler {
    private fun isTranslucentOrFloating(): Boolean {
        var isTranslucentOrFloating = false
        try {
            val styleableRes =
                Class.forName("com.android.internal.R\$styleable").getField("Window").get(null) as IntArray
            val ta = obtainStyledAttributes(styleableRes)
            val m = ActivityInfo::class.java.getMethod("isTranslucentOrFloating", TypedArray::class.java)
            m.isAccessible = true
            isTranslucentOrFloating = m.invoke(null, ta) as Boolean
            m.isAccessible = false
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return isTranslucentOrFloating
    }




    override fun onReq(p0: BaseReq?) {
        finish()
    }

    override fun onResp(resp: BaseResp?) {
        logprocess("BaseResp:$resp errorCode:${resp?.errCode} openId:${resp?.openId} errStr：${resp?.errStr} transtion:${resp?.transaction}")
        if (resp == null) {
            finish()
            return
        }
        if (resp is SendAuth.Resp){
            logprocess("resp:$resp errorCode:${resp.errCode} openId:${resp.openId} errStr：${resp.errStr} transtion:${resp.transaction} code:${resp.code} ")
            if (resp.errCode == 0) {
                when (resp.transaction) {
                    AccountReqType.LOGIN -> {
                        LiveEventBus.get(AccountLoginEvent::class.java).post(AccountLoginEvent(resp.code))
                    }
                    AccountReqType.Auth -> {//授权
                        LiveEventBus.get(AccountAuthEvent::class.java).post(AccountAuthEvent(resp.code))
                    }
                }

            }
        }else if (resp is WXLaunchMiniProgram.Resp){
            if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM){
                val extraData: String = resp.extMsg
                logprocess("extradata:$extraData")
            }
        }

        finish()
    }


    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        ThirdAccountHelper.wxApi.handleIntent(intent, this)
    }

    override fun onCreate(p0: Bundle?) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            val result = fixOrientation()
        }
        super.onCreate(p0)
        try {
            val intent = intent
            ThirdAccountHelper.wxApi.handleIntent(intent, this)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


    private fun fixOrientation(): Boolean {
        try {
            val field = Activity::class.java.getDeclaredField("mActivityInfo")
            field.isAccessible = true
            val o = field.get(this) as ActivityInfo
            o.screenOrientation = -1
            field.isAccessible = false
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return false
    }


}